package com.hengtongxing.hejiayun.shop;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.hengtongxing.hejiayun.R;
import com.hengtongxing.hejiayun.base.BaseActivity;
import com.hengtongxing.hejiayun.base.DataCallBack;
import com.hengtongxing.hejiayun.bean.AddressListBean;
import com.hengtongxing.hejiayun.bean.CreateOrderBean;
import com.hengtongxing.hejiayun.bean.ShopCartBean;
import com.hengtongxing.hejiayun.bean.ShopCartListBean;
import com.hengtongxing.hejiayun.event.AddressEvent;
import com.hengtongxing.hejiayun.event.CartRefushEvent;
import com.hengtongxing.hejiayun.event.ChooseAddressEvent;
import com.hengtongxing.hejiayun.mine.AddAddressActivity;
import com.hengtongxing.hejiayun.mine.AddressListActivity;
import com.hengtongxing.hejiayun.mine.model.IMineModel;
import com.hengtongxing.hejiayun.mine.model.MineModelImpl;
import com.hengtongxing.hejiayun.shop.adapter.ShopConfirmOrderListAdapter;
import com.hengtongxing.hejiayun.shop.model.IShopModel;
import com.hengtongxing.hejiayun.shop.model.ShopModelImpl;
import com.hengtongxing.hejiayun.utils.FastClickUtils;
import com.hengtongxing.hejiayun.utils.NumberFormatUtils;
import com.hengtongxing.hejiayun.utils.ToastUtil;
import com.hengtongxing.hejiayun.widget.AppTitleBar;
import com.hengtongxing.hejiayun.widget.ViewLoading;
import com.hengtongxing.hejiayun.widget.WrapContentLinearLayoutManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ShopConfirmOrderActivity extends BaseActivity {
    @BindView(R.id.title_bar)
    AppTitleBar titleBar;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_mobile)
    TextView tvMobile;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.ll_select_address)
    LinearLayout llSelectAddress;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.tv_total_number)
    TextView tvTotalNumber;
    @BindView(R.id.tv_total_price)
    TextView tvTotalPrice;
    @BindView(R.id.tv_total_number2)
    TextView tvTotalNumber2;
    @BindView(R.id.tv_total_price2)
    TextView tvTotalPrice2;
    @BindView(R.id.tv_commit)
    TextView tvCommit;
    @BindView(R.id.edit_remark)
    EditText editRemark;
    private List<ShopCartListBean.DataBean.ItemListBean> beanList;
    private ShopConfirmOrderListAdapter listAdapter;
    private IMineModel mineModel;
    private String totalPrice = "0";
    private int goodsNum;
    private AddressListBean.DataBean.ItemListBean addressBean;
    private IShopModel shopModel;
    private String type;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_confirm_order);
        ButterKnife.bind(this);
        registerEventBus();
        initView();
        requestAddressIndex();
    }

    @Subscribe
    public void addressEvent(ChooseAddressEvent event) {
        addressBean = event.getItemListBean();
        tvName.setText(addressBean.getName());
        tvMobile.setText(addressBean.getMobile());
        tvAddress.setText(addressBean.getProvince() + addressBean.getCity() + addressBean.getArea() + addressBean.getAddress());
        tvAddress.setVisibility(View.VISIBLE);
    }

    @Subscribe
    public void addressEvent(AddressEvent event) {
        requestAddressIndex();
    }

    private void initView() {
        shopModel = new ShopModelImpl();
        mineModel = new MineModelImpl();
        type = getIntent().getStringExtra("type");
        beanList = (List<ShopCartListBean.DataBean.ItemListBean>) getIntent().getSerializableExtra("itemList");

        if (beanList != null) {
            for (ShopCartListBean.DataBean.ItemListBean itemListBean : beanList) {
                goodsNum = goodsNum + itemListBean.getNum();
                totalPrice = NumberFormatUtils.formatDouble(Double.parseDouble(totalPrice) + itemListBean.getNum() * Double.parseDouble(itemListBean.getPrice()) / 100);
            }
        }
        tvTotalNumber.setText("共" + goodsNum + "件");
        tvTotalNumber2.setText("共" + goodsNum + "件，");
        tvTotalPrice.setText(totalPrice);
        tvTotalPrice2.setText(totalPrice);


        recyclerView.setLayoutManager(new WrapContentLinearLayoutManager(mActivity));
        listAdapter = new ShopConfirmOrderListAdapter(beanList);
        recyclerView.setAdapter(listAdapter);
        listAdapter.setOnCallBackListener((type, position) -> {

        });
    }

    private void requestAddressIndex() {
        mineModel.requestAddressIndex(1, new DataCallBack<AddressListBean>() {
            @Override
            public void onSuccessful(AddressListBean bean) {
                if (bean.getData().getItemList() != null && bean.getData().getItemList().size() > 0) {
                    addressBean = bean.getData().getItemList().get(0);
                    tvName.setText(addressBean.getName());
                    tvMobile.setText(addressBean.getMobile());
                    tvAddress.setText(addressBean.getProvince() + addressBean.getCity() + addressBean.getArea() + addressBean.getAddress());
                    tvAddress.setVisibility(View.VISIBLE);
                } else {
                    tvName.setText("暂无收货地址请添加");
                    tvMobile.setText("");
                    tvAddress.setText("");
                    tvAddress.setVisibility(View.GONE);
                }

            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }


    @OnClick({R.id.ll_select_address, R.id.tv_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_select_address:
                if (addressBean == null) {
                    showActivity(AddAddressActivity.class);
                } else {
                    Intent intent = new Intent(mActivity, AddressListActivity.class);
                    intent.putExtra("chooseType", "select_address");
                    startActivity(intent);
                }
                break;
            case R.id.tv_commit:
                if (beanList == null) {
                    return;
                }
                if (FastClickUtils.isFastClick()) {
                    return;
                }
                if (addressBean == null) {
                    ToastUtil.showShort("请添加收货地址");
                    return;
                }
                requestStoreOrderAdd();
                break;

        }
    }

    /**
     * 创建订单
     */
    public void requestStoreOrderAdd() {
        List<ShopCartBean> mList = new ArrayList<>();
        for (ShopCartListBean.DataBean.ItemListBean itemListBean : beanList) {
            mList.add(new ShopCartBean(String.valueOf(itemListBean.getNum()),
                    String.valueOf(itemListBean.getGoods_id()),
                    String.valueOf(itemListBean.getId()),
                    String.valueOf(itemListBean.getNorm_id()),
                    String.valueOf(itemListBean.getType()), itemListBean.getMid()));
        }
        ViewLoading.showProgress(mActivity, "提交中......");
        if (!TextUtils.isEmpty(type)) {
            shopModel.requestIntegralGoodsFastAdd(addressBean.getId() + "", "1",
                    editRemark.getText().toString(), mList, new DataCallBack<CreateOrderBean>() {
                        @Override
                        public void onSuccessful(CreateOrderBean bean) {
                            EventBus.getDefault().post(new CartRefushEvent());
                            ToastUtil.showShort("下单成功");
                            List<String>  list = Arrays.asList(bean.getData().getId());
                            Intent intent = new Intent(mActivity, ShopPayOrderActivity.class);
                            intent.putExtra("order_no", (Serializable) list);
                            intent.putExtra("totalPrice", totalPrice);
                            intent.putExtra("payPage", "ConfirmOrderActivity");
                            startActivity(intent);
                            finish();
                        }

                        @Override
                        public void onFailed(String msg, String code) {

                        }
                    });
        } else {
            shopModel.requestIntegralGoodsCreate(addressBean.getId() + "", "1",
                    editRemark.getText().toString(), mList, new DataCallBack<CreateOrderBean>() {
                        @Override
                        public void onSuccessful(CreateOrderBean bean) {
                            EventBus.getDefault().post(new CartRefushEvent());
                            ToastUtil.showShort("下单成功");
                            List<String>  list = Arrays.asList(bean.getData().getId());
                            Intent intent = new Intent(mActivity, ShopPayOrderActivity.class);
                            intent.putExtra("order_no", (Serializable) list);
                            intent.putExtra("totalPrice", totalPrice);
                            intent.putExtra("payPage", "ConfirmOrderActivity");
                            startActivity(intent);
                            finish();
                        }

                        @Override
                        public void onFailed(String msg, String code) {

                        }
                    });
        }

    }
}
